package com.hallowd.purcom;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.LoginFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;


public class LoginActivity extends Activity {
    private static final String TAG = LoginActivity.class.getSimpleName();

    Button mLoginButton;
    EditText mEmail;
    EditText mPassword;
    TextView mSignUpLink;
    Activity myActivity;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mEmail = (EditText) findViewById(R.id.email);
        mPassword = (EditText) findViewById(R.id.password);
        mLoginButton = (Button) findViewById(R.id.loginButton);
        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                (new LoginAsyncTask()).execute();
            }
        });

        myActivity = this;

        mSignUpLink = (TextView) findViewById(R.id.signUpLink);
        mSignUpLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
                startActivity(intent);
            }
        });
    }


    private class LoginAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = "http://titan.cmpe.boun.edu.tr:8089/purcom/mobile/user/signin/";
            String email = mEmail.getText().toString();
            String password = mPassword.getText().toString();
            url = url + "?email="+email+"&password="+password;

            HttpClient httpclient = new DefaultHttpClient();
            HttpUriRequest request = new HttpGet(url);

            try {
                HttpResponse response = httpclient.execute(request);
                if (response.getStatusLine().getStatusCode() == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

                    StringBuilder builder = new StringBuilder();
                      for (String line = null; (line = reader.readLine()) != null; ) {
                        builder.append(line).append("\n");
                    }

                    Log.d(TAG, "Login "+builder.toString());
                    return builder.toString();
                }
                else
                    Log.d(TAG, "Login Failed");
            } catch (IOException e) {
                Log.d(TAG, "Connection problem occured");
            }

            return null;
        }

        protected void onPostExecute(String result) {
            if(result == null){
                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                builder.setMessage("Login failed.")
                        .setTitle("Result")
                        .setPositiveButton(android.R.string.ok, null);
                AlertDialog dialog = builder.create();
                dialog.show();
                return;
            }

            JSONObject userJSON=null;
            try{
                userJSON = new JSONObject(result);
            }catch(Exception ex){
                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                builder.setMessage("Login failed.")
                        .setTitle("Result")
                        .setPositiveButton(android.R.string.ok, null);
                AlertDialog dialog = builder.create();
                dialog.show();
                return;
            }


            SharedPreferences pref = getApplicationContext().getSharedPreferences("purcomPref", MODE_PRIVATE);
            SharedPreferences.Editor editor = pref.edit();

            Long userId = null;
            try {
                userId= (Long) userJSON.getLong("id");
            }catch(Exception ex){
                userId = null;
                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                builder.setMessage("Login failed.")
                        .setTitle("Result")
                        .setPositiveButton(android.R.string.ok, null);
                AlertDialog dialog = builder.create();
                dialog.show();
                return;
            }

            editor.putLong("userID",userId);
            editor.commit();
            Log.i("Succesful login", result);

            // oguz test git commit
            Intent myintent = new Intent(myActivity,wellcomePageActivity.class);
            startActivity(myintent);

        }
    }

}
